<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="divWarehouse">
    <div class="divHead">
      <ITinput />
    </div>
    <div class="divContent">
      <div class="a6666">
        <div>
          <el-button
            style="margin-bottom: 20px"
            type="success"
            round
            plain
            @click="$router.push('newWarehouseLocation')"
            >新增仓库</el-button
          >
        </div>
        <div class="a56453">
          <el-button
            style="margin-bottom: 20px"
            round
            plain
            @click="exportClick"
            >下载库区模板</el-button
          >
          <el-upload
            action="/上传文件的接口"
            :on-change="onChange"
            :auto-upload="false"
            :show-file-list="false"
            accept=".xls, .xlsx"
            ref="upload"
            :multiple="true"
          >
            <el-button style="margin-bottom: 20px" round plain
              >导入库区信息</el-button
            >
          </el-upload>
        </div>
      </div>
      <template>
        <el-table
          id="mainTable"
          border
          :row-class-name="tableRowClassName"
          style="font-size: 10px"
          :header-cell-style="{
            background: '#f9f6ee',
            'text-align': 'center',
          }"
          :row-style="{ height: '0' }"
          :cell-style="{ padding: '3px', 'text-align': 'center' }"
          class="table_class"
          :data="tableData"
        >
          <el-table-column width="80" prop="number" label="序号">
            <template slot-scope="scope">
              <span v-text="getIndex(scope.$index)"> </span>
            </template>
          </el-table-column>

          <el-table-column width="120" prop="warehouseName" label="所属仓库">
          </el-table-column>

          <el-table-column width="120" prop="code" label="库区编号">
          </el-table-column>
          <el-table-column
            align="center"
            label="库区名称"
            prop="areaName"
            width="200px"
          >
          </el-table-column>

          <el-table-column width="120" prop="code" label="库位编号">
          </el-table-column>
          <el-table-column width="120" prop="name" label="库位名称">
          </el-table-column>
          <el-table-column
            prop="temperatureType"
            :formatter="temperatureType"
            label="温度类型"
            width="180px"
          >
          </el-table-column>

          <el-table-column
            :formatter="bearingType"
            width="120"
            prop="bearingType"
            label="承重类型"
          >
          </el-table-column>
          <el-table-column
            width="120"
            :formatter="useType"
            prop="useType"
            label="用途属性"
          >
          </el-table-column>
          <el-table-column
            width="120"
            :formatter="chkState"
            prop="status"
            label="库区状态"
          >
          </el-table-column>
          <el-table-column width="120" prop="maxVolume" label="承载上限">
          </el-table-column>
          <el-table-column
            width="150px"
            align="center"
            prop="updateTime"
            label="更新时间"
          >
          </el-table-column>
          <el-table-column
            align="center"
            width="200"
            prop="mobile"
            fixed="right"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="show(scope.row)" size="small"
                >编辑</el-button
              >
              <el-button
                v-show="scope.row.status == 1 ? true : false"
                @click="goon(scope.row, 0)"
                type="text"
                size="small"
                >停用</el-button
              >
              <el-button
                v-show="scope.row.status == 0 ? true : false"
                @click="goon(scope.row, 1)"
                type="text"
                size="small"
                >启用</el-button
              >
              <el-button @click="delFn" type="text" size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <PageTools
          ref="page"
          @pagesizeChange="pagesizeChange"
          @pageChange="pageChange"
          :total.sync="total"
        />
      </template>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import constants from '@/constant/status'
import { list, location } from '@/api/location.js'
export default {
  data () {
    return {
      page: {
        page: 1,
        pagesize: 10
      },
      tableData: [],
      total: ''
    }
  },
  async created () {
    this.list(this.page)
  },
  methods: {
    exportClick () {
      // 第一个参数是到处后文件名，第二个是id绑定表格dom
      this.exportExcel('test', 'mainTable')
    },
    // 转换数据
    exportExcel (filename, tableId) {
      const xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
      const table = document.querySelector('#' + tableId).cloneNode(true)
      const wb = XLSX.utils.table_to_book(table, xlsxParam)
      /* 获取二进制字符进行输出 */
      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          filename + '.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    },

    // 导入
    onChange (file, fileList) {
      this.readExcel(file) // 调用读取数据的方法
    },
    // 读取数据
    readExcel (file) {
      const that = this
      if (!file) {
        // 如果没有文件
        return false
      } else if (!/.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }
      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          if (workbook.SheetNames.length >= 1) {
            this.$message({
              message: '导入数据表格成功',
              showClose: true,
              type: 'success'
            })
          }
          const wsname = workbook.SheetNames[0] // 取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
          console.log('生成json：', ws)
          // that.tableData = [];
          for (let i = 2; i < ws.length; i++) {
            const sheetData = {
              // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
              date: ws[i]['日期'],
              name: ws[i]['配送信息'],
              province: ws[i].__EMPTY,
              city: ws[i].__EMPTY_1,
              address: ws[i].__EMPTY_2,
              zip: ws[i].__EMPTY_3
            }
            console.log('上传的数据:', sheetData)
            // 添加到表格中
            that.tableData.push(sheetData)
            // 正常导入需要拿到上传的数据就在这从新弄个数组push进去，然后传给后台，后台保存后查询表格返给前端。
          }
          this.$refs.upload.value = ''
        } catch (e) {
          console.log(e)
          return false
        }
      }
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(file.raw)
    },

    show (row) {
      console.log(row)
      this.$router.push({
        path: 'newWarehouseLocation',
        query: {
          key: row
        }
      })
    },
    async list (page) {
      const {
        data: { data }
      } = await list(page)
      this.tableData = data.records
      this.total = data.total
    },
    tableRowClassName ({ row, rowIndex }) {
      if (rowIndex === 1 || rowIndex === 3) {
        return 'warning-row'
      } else if (rowIndex === 0 || rowIndex === 2) {
        return 'success-row'
      }
      return ''
    },
    async pagesizeChange (e) {
      this.page.pagesize = e
      await this.list(this.page)
    },
    async pageChange (e) {
      this.page.page = e
      await this.list(this.page)
      // console.log(1);
      // this.$refs.page.handleCurrentChange;
    },
    // 序号
    getIndex ($index) {
      return (this.page.page - 1) * this.page.pagesize + $index + 1
    },
    // 仓库状态
    chkState (row, column, cellValue, index) {
      const obj = constants.status.find((item) => {
        return item.value === cellValue
      })
      return obj ? obj.label : '未知'
    },
    // 仓库类型
    bearingType (row, column, cellValue, index) {
      const obj = constants.bearingType.find((item) => {
        return item.value === cellValue
      })
      return obj ? obj.label : '未知'
    },
    temperatureType (row, column, cellValue, index) {
      const obj = constants.temperatureType.find((item) => {
        return item.value === cellValue
      })
      return obj ? obj.label : '未知'
    },
    useStatus (row, column, cellValue, index) {
      const obj = constants.useStatus.find((item) => {
        return item.value === cellValue
      })
      return obj ? obj.label : '未知'
    },
    useType (row, column, cellValue, index) {
      const obj = constants.useType.find((item) => {
        return item.value === cellValue
      })
      return obj ? obj.label : '未知'
    },
    delFn () {
      this.$notify({
        title: '警告',
        message: '哥哥你laver不够呢',
        type: 'warning'
      })
    },
    // 上架下架功能
    async goon (row, publishState) {
      if (publishState === 0) {
        const a = {}
        a.id = row.id
        a.status = publishState
        this.$confirm('宝贝您确认停用嘛?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            // row.publishState = publishState
            await location(a)
            await this.list(this.page)

            this.$message({
              type: 'success',
              message: '成功了!'
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '怎么取消了呢!'
            })
          })
      } else if (publishState === 1) {
        const a = {}
        a.id = row.id
        a.status = publishState
        this.$confirm('宝贝您确认启用嘛?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            console.log(1)
            // row.publishState = publishState
            const res = await location(a)
            console.log(res)
            await this.list(this.page)

            this.$message({
              type: 'success',
              message: '成功了!'
            })
          })
          .catch((res) => {
            console.log(res)
            this.$message({
              type: 'info',
              message: '怎么取消了呢!'
            })
          })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.a56453 {
  display: flex;
  justify-content: space-between;
}
.a6666 {
  display: flex;
  justify-content: space-between;
}
::v-deep .el-table .warning-row {
  background: #fdfcf9;
}

::v-deep .el-table .success-row {
  background: #ffffff;
}

.el-button--text {
  color: #ffb252;
}

::v-deep .el-table__body tr.hover-row > td.el-table__cell {
  background-color: #fff6e2;
  /* color: #f19944; */ /* 设置文字颜色，可以选择不设置 */
}
.divWarehouse {
  margin: 20px;
  .divHead {
    height: 80px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 0 6px 0 rgb(144 142 142 / 17%);
    padding: 30px;
    margin-bottom: 20px;
  }
  .divContent {
    // height: 450px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 0 6px 0 rgb(144 142 142 / 17%);
    padding: 30px;
    padding-bottom: 0px;
    margin-bottom: 20px;
  }
}
::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
}
.table_class {
  &::v-deep {
    .el-table__body-wrapper::-webkit-scrollbar {
      /*width: 0;宽度为0隐藏*/
      width: 4px;
      height: 10px;
    }
    .el-table__body-wrapper::-webkit-scrollbar-thumb {
      border-radius: 6px;
      box-shadow: inset 0 0 5px rgba(247, 227, 170, 0.9);
      background: rgba(247, 227, 170, 0.9); //滚动条颜色
    }
    .el-table__body-wrapper::-webkit-scrollbar-track {
      box-shadow: inset 0 0 5px rgba(247, 179, 179, 0.8);
      border-radius: 6px;

      background: rgb(255, 255, 255); //滚动条背景色
    }
  }
}
</style>
